import {messages} from "share/common";
import React, { Component } from 'react';
import { connect } from "react-redux";
import { message } from "antd";
import SettingService from 'containers/finance-setting/loan-setting/setting-service'

const SaveHoc = WrappedComponent => {
  class hoc extends Component {

    setWrappedInstance = ref => {
      this.wrappedInstance = ref;
    };

    handleSave = (url, value, listName) => {
      const { priority } = this.wrappedInstance.state, { record } = this.props.params, { tenant, close } = this.props;
      if (!priority || (priority.distribution && priority.distribution.companies.length === 0)) {
        message.error(messages('finance-1.key371')/*请分配权限*/);
        return -1;
      }
      let res = Object.assign({ tenantId: tenant.id }, record, value, priority);
      let distributionList = res.distribution;
      delete res.distribution;
      res.isGlobal = !distributionList;
      distributionList && (res[listName] = distributionList.companies.map(item => ({
        levelCode: 'COMPANY',
        levelOrgId: item.id,
        levelOrgName: item.name,
        tenantId: tenant.id
      })));
      this.wrappedInstance.setState({ saveLoading: true });
      SettingService[url](res).then(() => {
        this.wrappedInstance.setState({ saveLoading: false }, () => {
          message.success(messages('common.operate.success')/*操作成功*/);
          close(true);
        });
      }).catch(e => {
        message.error(e.response.data.message);
        this.wrappedInstance.setState({ saveLoading: false });
      })
    };

    render() {
      let props = { ...this.props, ref: this.setWrappedInstance };
      return (
        <WrappedComponent {...props} handleSave={this.handleSave}/>
      )
    }

  }

  function mapStateToProps(state) {
    return {
      tenant: state.login.tenant
    }
  }

  return connect(mapStateToProps)(hoc);
};

export default SaveHoc;
